<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\goods\admin;

use app\goods\model\Product as ProductModel;
use app\goods\model\Brand as BrandModel;
use app\goods\model\GoodsClass as GoodsClassModel;
use app\goods\model\Color as ColorModel;
use app\goods\model\ColorGroup as ColorGroupModel;
use app\goods\model\SizeGroup as SizeGroupModel;
use app\goods\model\Size as SizeModel;
use app\goods\model\CodeRule as CodeRuleModel;
use app\goods\model\Activites as ActivitesModel;
use app\shop\model\Shop as ShopModel;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Cache;
use think\Db;

/**
 * 商品管理
 * @package app\admin\controller
 */
class Product extends Admin
{
    /**
    *商品列表
    */
    public function index(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $order = $this->getOrder('goods_class.sort ASC,goods_size.sort ASC,update_time DESC,goodsid DESC');
        $where = $this->getMap();
        $where['isdel'] = 0;
    	$data_list = ProductModel::goodsSelect($where,$order);

        $js = <<<EOF
            <script type="text/javascript">
                $(function(){
                    var s = 1;
                    $('select[name=styleid]').change(function(){
                        if(s == 1){
                        alert('改变类型可能会丢失部分属性');
                        s = 2;
                    }

                    })
                });
            </script>
EOF;


        return ZBuilder::make('table')
        ->addOrder('goodsid')
        ->addTimeFilter('create_time')
        ->addFilter(['goodsid' => 'goods_list.goodsid', 'goodsname' => 'goods_list.goodsname', 'goodsno' => 'goods_list.goodsno', 'othername' => 'goods_list.othername', 'classname' => 'goods_class.artno', 'brandname' => 'goods_brand.brandname', 'crowdname' => 'goods_crowd.crowdname', 'unitname' => 'goods_unit.unitname', 'colorgroupname' => 'goods_colorgroup.groupname', 'colorname' => 'goods_color.name', 'sizegroupname' => 'goods_sizegroup.groupname', 'sizename' => 'goods_size.name', 'goodsno' => 'goods_list.goodsno'])
        ->addFilter(['status' => 'goods_list.status'],['0' => '下架', '1' => '上架'])
        ->addFilter(['checkstatus' => 'goods_list.checkstatus'],['0' => '未审核', '1' => '已审核'])
        ->addFilter(['bedit' => 'goods_list.bedit'],['0' => '未审核', '1' => '已审核'])
        ->addColumns([ // 批量添加列
            ['goodsno', '编码', '', '', '', 'fix-table-td'],
            ['goodsname', '名称', '', '', '', 'fix-table-td'],
            ['classname', '款号'],
            ['colorname', '颜色'],
            ['sizename', '尺码'],
            ['status', '上架', 'status', '', ['下架','上架']],
            ['checkstatus', '审核', 'status', '', ['未审核','已审核']],
            ['bedit', '编辑', 'status', '', ['未审核','已审核']],
            /*['update_time', '修改时间', 'datetime'],
            ['create_time', '创建时间', 'datetime'],*/
            ['right_button', '操作', 'btn']
        ])
        ->setTableName('goods_list')
        ->setPrimaryKey('goodsid')
        ->addRightButton('edit', ['href' => url('show',['id' => '__id__']), 'icon' => 'fa fa-fw fa-crosshairs', 'title' => '查看'], true)
        ->addRightButton('edit')
        ->addRightButton('delete')
        ->addTopButton('add')
        /*->addTopButton('add', ['title' => '导入库存', 'icon' => 'fa fa-fw fa-briefcase', 'href'=> url('addstock'), 'class' => 'btn btn-danger'], true)*/
        ->addTopButton('custom', ['title' => '上架', 'icon' => 'fa fa-fw fa-download', 'href'=> url('product/addstock',['name' => '库存']), 'class' => 'btn btn-info'], true)
        ->addTopButton('custom', ['title' => '模板', 'icon' => 'fa fa-fw fa-download', 'href'=> url('price/downloadtpl',['name' => 'stock.xlsx']), 'class' => 'btn btn-info'])
        /*->addTopButton('enable', ['field' => 'status', 'title' => '上架'])*/
        ->addTopButton('disable', ['field' => 'status', 'title' => '下架'])
        ->addTopButton('enable', ['field' => 'checkstatus', 'title' => '审核'])
        ->addTopButton('enable', ['field' => 'bedit', 'title' => '编辑'])
        ->addTopButton('add', ['title' => '导入', 'icon' => 'fa fa-fw fa-pencil-square-o', 'href'=> url('leading'), 'class' => 'btn btn-danger'], true)
        ->addTopButton('custom', ['title' => '导出', 'icon' => 'fa fa-fw fa-download', 'href'=> url('export'), 'class' => 'btn btn-info js-get'])
       
        ->addTopButton('custom', ['title' => '模板', 'icon' => 'fa fa-fw fa-download', 'href'=> url('price/downloadtpl',['name' => 'product.xlsx']), 'class' => 'btn btn-info'])
         ->addTopButton('add', ['title' => '回收站', 'icon' => 'fa fa-fw fa-trash-o', 'href'=> url('isdel'), 'class' => 'btn btn-default'])
        ->setRowList($data_list)
        ->setExtraJs($js)
        ->fetch();
    }


    /**
    *新增
    */

    public function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($data['hide'] == 1){
                if(empty($data['codeid']) || empty($data['classid']) || empty($data['brandid'])){
                    $this->error('请完善信息');
                }
                //颜色列表
                $color_list = ColorModel::where('brandid',$data['brandid'])->column('colorid,name');

                //尺码列表
                $size_list  = SizeModel::where('brandid',$data['brandid'])->column('sizeid,name');

                //经营类型列表
                $activites_list = ActivitesModel::where('status', '1')->column('activitesid,activitesname');

                return ZBuilder::make('form')
                    ->addFormItems([ // 批量添加列            
                        ['hidden', 'brandid', $data['brandid']],
                        ['hidden', 'classid', $data['classid']],
                        ['hidden', 'codeid',  $data['codeid']],
                        ['hidden', 'hide', '2'],
                        ['select','ownerid','选择店铺','','','','ajax','',['url'=>url('shoplist'),'datakey'=>'id','dataname'=>'name']],
                        ['select', 'activitesid', '经营类型', '', $activites_list],
                        ['number', 'cess', '税率'],
                        ['number', 'conversion', '标箱量'],
                        ['checkbox', 'colorid', '颜色', '<span style="color:red;">至少选择一种</span>',$color_list],
                        ['checkbox', 'sizeid', '尺码', '<span style="color:red;">至少选择一种</span>',$size_list],      
                        
                    ])
                    ->setPageTitle('【Step2】选值颜色、尺码')
                    ->setBtnTitle('submit', '生成SKU')
                    ->layout(['ownerid' => 3, 'cess' => 3, 'activitesid' => 3, 'conversion' => 4])
                    ->fetch();

            }else{
                $result = $this->validate($data, 'Product');
                if(true !== $result) return $this->error($result);
                if($data['cess'] < 0){
                    $this->error('税率必须大于0');
                }
                if($data['conversion'] <= 0){
                    $this->error('标箱量必须大于0');
                }
                $add_data['cess']        = $data['cess'];
                $add_data['conversion']  = $data['conversion'];
                $add_data['brandid']     = $data['brandid'];
                $add_data['classid']     = $data['classid'];
                $add_data['codeid']      = $data['codeid'];
                $add_data['ownerid']     = $data['ownerid']['0'];
                $add_data['activitesid'] = $data['activitesid'];
                $add_data['create_time'] = time();
                $add_data['update_time'] = time();
                $new_id                  = '';

                //款信息
                $class_info = GoodsClassModel::where('classid', $data['classid'])->find();

                $size_str   = '';
                $color_str  = '';
                foreach ($data['sizeid'] as $key => $value) {
                    //关联size
                    if(!strstr($class_info['sizebox'], ','.$value.',')){
                       $size_str .= $value.',';
                    }
                    foreach ($data['colorid'] as $k => $val) {
                        //关联color
                        if(!strstr($class_info['colorbox'], ','.$val.',')){
                            $color_str .= $val.',';
                        }
                        $add_data['goodsno']   = $this->code($data['codeid'], $data['classid'], $val, $value);
                        $goodsno[] = $add_data['goodsno'];
                        $add_data['goodsname'] = $this->goodsname($data['classid'], $val, $value);
                        $add_data['colorid']   = $val;
                        $add_data['sizeid']    = $value;
                        $add_data['colorgroupid'] = $this->colorgroup($val);
                        $add_data['sizegroupid']  = $this->sizegroup($value);
                        $id                       = ProductModel::where('goodsname', $add_data['goodsname'])->value('goodsid');

                        if($id > 0){
                            $add_data['isdel']   = 0;
                            $add_data['goodsid'] = $id;
                            $add_data['status']  = 0;
                            $add_data['bedit']   = 0;
                            $add_data['checkstatus'] = 0;
                            
                            ProductModel::update($add_data);
                            $new_id .= $id.',';
                        }else{
                            unset($add_data['goodsid']);
                            $new_id              .= ProductModel::insertGetid($add_data).',';
                        }

                        
                    }
                }
                if(!empty($new_id)){
                    if(empty($class_info['sizebox'])){
                        $class_info['sizebox'] = ',';
                    }
                    if(empty($class_info['colorbox'])){
                        $class_info['colorbox'] = ',';
                    }
                    GoodsClassModel::where('classid',$class_info['classid'])->update(['sizebox' => $class_info['sizebox'].$size_str]);
                    GoodsClassModel::where('classid',$class_info['classid'])->update(['colorbox' => $class_info['colorbox'].$color_str]);
                    $this->success('新增成功', url('addlist',['ids' => $new_id]));
                }
            }
            /*$data['create_time'] = time();
            $data['update_time'] = time();
            $result = ProductModel::insert($data);
            if($result) {
                $this->success('新增成功');
            }else{
                $this->error('新增失败');
            }*/
        }

        //品牌列表
        $brand_list = BrandModel::where('status', '1')->column('brandid,brandname');

        //款号
        $class_list = GoodsClassModel::where('status','1')->column('classid,artno');

        //编码规则
        $code_list  = CodeRuleModel::where('status',1)->column('codeid,codename');


        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列            
            ['select', 'brandid', '品牌', '<span class="text-danger">必选</span>', $brand_list ],
            ['select', 'classid', '款号', '<span class="text-danger">必选</span>', $class_list ],
            ['select', 'codeid', '编码规则', '<span class="text-danger">必选</span>', $code_list ],
            ['hidden', 'hide', '1'],      
            
        ])
        ->setPageTitle('【Step1】填写基本信息')
        ->isAjax(false)
        ->layout(['classid' => 4, 'brandid' => 4, 'codeid' => 4])
        ->fetch();
    }

    /**
    *修改
    */
    public function edit($id = 0){
        if ($id === 0) return $this->error('缺少参数');

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($data['cess'] < 0){
                $this->error('税率必须大于0');
            }
            if($data['conversion'] <= 0){
                $this->error('标箱量必须大于0');
            }
            $data['update_time'] = time();
            $data['bedit']  = 0;
            $data['status'] = 0;
            $data['checkstatus'] = 0;
            $result = ProductModel::update($data);
            if($result) {
                $this->success('修改成功', cookie('__forward__'));
            }else{
                $this->error('修改失败');
            }
        }

        //详情
        $info      = ProductModel::where('goodsid',$id)->find();
        if($info['bedit'] == 0){
            $this->error('该产品不予许编辑!');
        }

        //经营类型列表
        $activites_list = ActivitesModel::where('status', '1')->column('activitesid,activitesname');

        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列
            ['hidden', 'goodsid'],
            ['text', 'goodsno', '编号'],            
            ['text', 'goodsname', '名称'],
            ['number', 'conversion', '标箱量'],
            ['select', 'activitesid', '经营类型', '', $activites_list],
            ['number', 'cess', '税率'],
            ['image', 'front', '正面图'],
            ['image', 'opposite', '背面图'],
            ['image', 'side', '侧面图']            
        ])
        ->setFormData($info)
        ->layout(['goodsname' => 6, 'goodsno' => 6, 'conversion' => 4, 'cess' => 4, 'activitesid' => 4, 'front' => 4, 'opposite' => 4, 'side' => 4])
        ->fetch();
    }


    /**
    *获取款号
    */
    public function get_class(){
        $id = input('classgroupid');
        $data = Db::name('goods_class')->where(array('status' => '1','parentid' => $id))->column('classid,classname');
        $list = [];
        foreach ($data as $key => $value) {
            $list[]=['key' => $key, 'value' => $value];
        }
        $data_list['list'] = $list;
        $data_list['code'] = '1'; //判断状态
        $data_list['msg']  = '请求成功'; //回传信息
        return json($data_list);
    }



    /**
    *删除
    */
    public function delete($ids = 0){
        $id     = input('ids');
        $result = ProductModel::where(array('goodsid' => $id))->update(array('isdel' => '1'));
        if($result){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }


    /**
    *导出
    */
    public function export(){
        $data = $this->request->get();
        $where['goodsid'] = array('in',$data['ids']);
        $xlsName  = "SKU";
        $xlsCell  = array(
            ['goodsid', 'id'],
            ['goodsno', '编码'],
            ['goodsname', '名称'],
            ['classname', '款号'],
            ['brandname', '品牌'],
            ['colorgroupname', '色系'],
            ['colorname', '颜色'],
            ['sizegroupname', '尺系'],
            ['sizename', '尺码'],
            ['conversion', '标箱量'],
            ['cess', '税率'],
            ['weight', '重量'],
            ['minprice', '最低售价'],
            ['status', '上架'],
            ['checkstatus', '审核'],
            ['bedit', '编辑'],
            /*['update_time', '修改时间', 'datetime'],
            ['create_time', '创建时间', 'datetime'],*/
        );

        $count = ProductModel::view('goods_list', true)
            ->view('goods_class', 'artno classname', 'goods_class.classid=goods_list.classid', 'left')
            ->view('goods_colorgroup', 'groupname colorgroupname', 'goods_colorgroup.colorgroupid=goods_list.colorgroupid','left')
            ->view('goods_color',  'Name colorname',  'goods_color.colorid=goods_list.colorid','left')
            ->view('goods_sizegroup', 'groupname sizegroupname', 'goods_sizegroup.sizegroupid=goods_list.sizegroupid','left')
            ->view('goods_size',   'Name sizename',   'goods_size.sizeid=goods_list.sizeid','left')
            ->view('goods_brand', 'brandname', 'goods_brand.brandid=goods_list.brandid', 'left')
            ->where($where)
            ->count();
        $filename = 'SKU'.date('_YmdHis');
        $xlsData  = [];
        $i = 0;
        $p = 1;
        do{
            $xlsData = ProductModel::exportSelect($where,'goodsid ASC', $p);
            $this->exportExcel(date('_YmdHis'), $xlsCell,$xlsData);
            $p += 1;
            $i += 1000;
            unset($xlsData);
        }while($i<= $count);

        $dbpath = "./public/uploads/exportzip/";
        $zippath = $dbpath;

        $bakup=$filename;
        //zip文件名
        $z=new \util\PHPZip(); //新建立一个zip的类
        $z->ZipAndDownload($dbpath."/".$bakup,$bakup); //添加指定目录
    }

   


    public function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = 'SKU'.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        import('util.PHPExcel', EXTEND_PATH, '.class.php');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
       // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));  
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
        } 
          // Miscellaneous glyphs, UTF-8   
        for($i=0;$i<$dataNum;$i++){
          for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), " ".$expTableData[$i][$expCellName[$j][0]]);
          }             
        }

        if(!file_exists($_SERVER['DOCUMENT_ROOT'] . "/public/uploads/exportzip/".$fileName."/")){
            mkdir($_SERVER['DOCUMENT_ROOT'] . "/public/uploads/exportzip/".$fileName."/",0777);
            chmod($_SERVER['DOCUMENT_ROOT'] . "/public/uploads/exportzip/".$fileName."/",0777);
        }
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter->save($_SERVER['DOCUMENT_ROOT']."/public/uploads/exportzip/".$fileName."/" . $xlsTitle.'.xlsx');
        /*header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
        $objWriter->save('php://output'); 
        exit;   */
    }

    /**
    *查找会员
    */
    public function shoplist(){
        $search=input('q');
        $where['name']   =['like',"%$search%"];
        $where['status'] = 1;
        $shop=ShopModel::field('id,name')->where($where)->select();
        $shop_list=[];
        $a= 0;
        foreach($shop as $value){
            $b = $a++;
            $key=$value['id'];
            $shop_list[$b]['id']=$key;
            $shop_list[$b]['name']=$value['name'];
        }
        return json(['items'=>$shop_list,'total_count'=>sizeof($shop_list)]);
    }

    /**
    *编码
    */
    public function code($codeid = 0, $classid = 0, $colorid = 0, $sizeid = 0){
        $code_info = CodeRuleModel::where('codeid',$codeid)->find();
            switch ($code_info['codevalue2']) {
                case '1':
                    $code_info['codevalue2'] = GoodsClassModel::where('classid',$classid)->value('customcode');
                    break;
                case '2':
                    $code_info['codevalue2'] = ColorModel::where('colorid',$colorid)->value('customcode');
                    break;
                case '3':
                    $code_info['codevalue2'] = SizeModel::where('sizeid',$sizeid)->value('customcode');
                    break;
                case '4':
                    $code_info['codevalue2'] = GoodsClassModel::where('classid',$classid)->value('artno');
                    break;
                case '5':
                    $code_info['codevalue2'] = ColorModel::where('colorid',$colorid)->value('name');
                    break;
                case '6':
                    $code_info['codevalue2'] = SizeModel::where('sizeid',$sizeid)->value('name');
                    break;
            }

            switch ($code_info['codevalue4']) {
                case '1':
                    $code_info['codevalue4'] = GoodsClassModel::where('classid',$classid)->value('customcode');
                    break;
                case '2':
                    $code_info['codevalue4'] = ColorModel::where('colorid',$colorid)->value('customcode');
                    break;
                case '3':
                    $code_info['codevalue4'] = SizeModel::where('sizeid',$sizeid)->value('customcode');
                    break;
                case '4':
                    $code_info['codevalue4'] = GoodsClassModel::where('classid',$classid)->value('artno');
                    break;
                case '5':
                    $code_info['codevalue4'] = ColorModel::where('colorid',$colorid)->value('name');
                    break;
                case '6':
                    $code_info['codevalue4'] = SizeModel::where('sizeid',$sizeid)->value('name');
                    break;
            }

            switch ($code_info['codevalue6']) {
                case '1':
                    $code_info['codevalue6'] = GoodsClassModel::where('classid',$classid)->value('customcode');
                    break;
                case '2':
                    $code_info['codevalue6'] = ColorModel::where('colorid',$colorid)->value('customcode');
                    break;
                case '3':
                    $code_info['codevalue6'] = SizeModel::where('sizeid',$sizeid)->value('customcode');
                    break;
                case '4':
                    $code_info['codevalue2'] = GoodsClassModel::where('classid',$classid)->value('artno');
                    break;
                case '5':
                    $code_info['codevalue6'] = ColorModel::where('colorid',$colorid)->value('name');
                    break;
                case '6':
                    $code_info['codevalue6'] = SizeModel::where('sizeid',$sizeid)->value('name');
                    break;
            }
        $code = '';
        $code = $code_info['codevalue1'].$code_info['codevalue2'].$code_info['codevalue3'].$code_info['codevalue4'].$code_info['codevalue5'].$code_info['codevalue6'].$code_info['codevalue7'];
        return $code;

    }

    /**
    *名称
    */
    public function goodsname($classid = 0, $colorid = 0, $sizeid = 0){
        $classname = GoodsClassModel::where('classid',$classid)->value('classname');
        $colorname = ColorModel::where('colorid', $colorid)->value('name');
        $sizename  = SizeModel::where('sizeid', $sizeid)->value('name');
        $name = '';
        $name= $classname.$colorname.$sizename;
        return $name;
    }

    public function sizegroup($sizeid = 0){
        $sizegroupid = SizeModel::where('sizeid' ,$sizeid)->value('sizegroupid');
        return $sizegroupid;
    }

    public function colorgroup($colorid = 0){
        $colorgroupid = ColorModel::where('colorid' ,$colorid)->value('colorgroupid');
        return $colorgroupid;
    }


    /**
    *新增列表
    */
    public function addlist($ids = ''){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $order = $this->getOrder('goods_class.sort ASC,goods_size.sort ASC,update_time DESC,goodsid DESC');
        $where = $this->getMap();
        $where['goodsid'] = array('in',$ids);
        $where['isdel']   = 0;
        $data_list = ProductModel::goodsSelect($where,$order);
        return ZBuilder::make('table')
        ->addOrder('goodsid')
        ->addFilter(['goodsid' => 'goods_list.goodsid', 'goodsname' => 'goods_list.goodsname', 'goodsno' => 'goods_list.goodsno', 'othername' => 'goods_list.othername', 'classname' => 'goods_class.classname', 'brandname' => 'goods_brand.brandname', 'crowdname' => 'goods_crowd.crowdname', 'unitname' => 'goods_unit.unitname', 'colorgroupname' => 'goods_colorgroup.groupname', 'colorname' => 'goods_color.name', 'sizegroupname' => 'goods_sizegroup.groupname', 'sizename' => 'goods_size.name'])
        ->addColumns([ // 批量添加列
            ['goodsno', '编码', 'text.edit', '', '', 'fix-table-td'],
            ['goodsname', '名称', 'text.edit', '', '', 'fix-table-td'],
            ['cess', '税率', 'text.edit'],
            ['conversion', '标箱量', 'text.edit'],
            ['classname', '款号'],
            ['colorname', '颜色'],
            ['sizename', '尺码'],
            /*['status', '上架', 'status', '', ['上架','下架']],
            ['checkstatus', '审核', 'status', '', ['未审核','已审核']],
            ['bedit', '编辑', 'status', '', ['未审核','已审核']],*/
            
            ['right_button', '操作', 'btn']
        ])
        ->setTableName('goods_list')
        ->setPrimaryKey('goodsid')
        /*->addRightButton('edit')*/
        
        ->addTopButton('add',['title' => '确定', 'href' => url('index')])
        /*->addTopButton('enable', ['field' => 'status', 'title' => '上架'])
        ->addTopButton('disable', ['field' => 'status', 'title' => '下架'])
        ->addTopButton('enable', ['field' => 'checkstatus', 'title' => '审核'])
        ->addTopButton('enable', ['field' => 'bedit', 'title' => '编辑'])
        ->addTopButton('custom', ['title' => '编码', 'icon' => 'fa fa-fw fa-pencil-square-o', 'href'=> 'goodsno', 'class' => 'btn btn-danger ajax-post'])
        ->addTopButton('custom', ['title' => '导出', 'icon' => 'fa fa-fw fa-download', 'href'=> 'export', 'class' => 'btn btn-info ajax-post'])*/
        ->setRowList($data_list)
        ->addRightButton('edit', ['href' => url('show',['id' => '__id__']), 'icon' => 'fa fa-fw fa-crosshairs', 'title' => '查看'], true)
        ->addRightButton('delete')
        ->noPages()
        ->fetch();
    }


    public function get_color(){
        $id = input('brandid');
        $data = ColorModel::where(array('status' => '1','brandid' => $id))->column('colorid,name');
        $list = [];
        foreach ($data as $key => $value) {
            $list[]=['key' => $key, 'value' => $value];
        }
        $data_list['list'] = $list;
        $data_list['code'] = '1'; //判断状态
        $data_list['msg']  = '请求成功'; //回传信息
        return json($data_list);
    }

    /**
    *获取尺码
    */
    public function get_size(){
        $id = input('colorid');
        $brandid = ColorModel::where('colorid',$id)->value('brandid');
        $data = SizeModel::where(array('status' => '1','brandid' => $brandid))->column('sizeid,name');
        $list = [];
        foreach ($data as $key => $value) {
            $list[]=['key' => $key, 'value' => $value];
        }
        $data_list['list'] = $list;
        $data_list['code'] = '1'; //判断状态
        $data_list['msg']  = '请求成功'; //回传信息
        return json($data_list);
    }

    public function show($id = 0){
        $info = ProductModel::show($id);
        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列
            ['static', 'goodsid', 'id'],
            ['static', 'goodsno', '编号'],            
            ['static', 'goodsname', '名称'],
            ['static', 'classname', '款号'],
            ['static','shopname','店铺'],
            ['static','activitesid','经营类型'],
            ['static', 'brandname', '品牌'],
            ['static', 'colorgroupname', '色系'],
            ['static', 'colorname', '颜色'],
            ['static', 'sizegroupname', '尺码组'],
            ['static', 'sizename', '尺码'],
            ['static', 'conversion', '标箱量'],
            ['static', 'cess', '税率'],  
            ['static', 'codename', '编码规则'],
            ['static', 'weight', '重量'],
            ['static', 'minprice', '最低售价'],
            ['static', 'status', '上架状态'],
            ['static', 'checkstatus', '审核状态'],
            ['static', 'bedit', '编辑审核'],
            ['static', 'update_time', '更新时间'],
            ['static', 'create_time', '创建时间'],

        ])
        ->setFormData($info)
        ->layout(['goodsname' => 3, 'activitesid' => 3, 'brandname' => 3, 'classname' => 3, 'colorname' => 3, 'sizename' => 3, 'goodsno' => 3, 'shopname' => 3, 'conversion' => 3, 'cess' => 3, 'goodsid' => 3, 'sizegroupname' => 3, 'colorgroupname' => 3, 'codename' => 3, 'status' => 3, 'checkstatus' => 3, 'bedit' => 3, 'update_time' => 3, 'create_time' => 3, 'weight' => 3, 'minprice' => 3])
        ->hideBtn('submit')
        ->fetch();
    }


    public function isdel(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $order = $this->getOrder('goods_class.sort ASC,goods_size.sort ASC,update_time DESC,goodsid DESC');
        $where = $this->getMap();
        $where['isdel'] = 1;
        $data_list = ProductModel::goodsSelect($where,$order);
        return ZBuilder::make('table')
        ->addOrder('goodsid')
        ->addFilter(['goodsid' => 'goods_list.goodsid', 'goodsname' => 'goods_list.goodsname', 'goodsno' => 'goods_list.goodsno', 'othername' => 'goods_list.othername', 'classname' => 'goods_class.classname', 'brandname' => 'goods_brand.brandname', 'crowdname' => 'goods_crowd.crowdname', 'unitname' => 'goods_unit.unitname', 'colorgroupname' => 'goods_colorgroup.groupname', 'colorname' => 'goods_color.name', 'sizegroupname' => 'goods_sizegroup.groupname', 'sizename' => 'goods_size.name', 'goodsno' => 'goods_list.goodsno'])
        ->addColumns([ // 批量添加列
            ['goodsno', '编码', '', '', '', 'fix-table-td'],
            ['goodsname', '名称', '', '', '', 'fix-table-td'],
            ['classname', '款号'],
            ['colorname', '颜色'],
            ['sizename', '尺码'],
            ['status', '上架', 'status', '', ['下架','上架']],
            ['checkstatus', '审核', 'status', '', ['未审核','已审核']],
            ['bedit', '编辑', 'status', '', ['未审核','已审核']],
            /*['update_time', '修改时间', 'datetime'],
            ['create_time', '创建时间', 'datetime'],*/
            ['right_button', '操作', 'btn']
        ])
        ->setTableName('goods_list')
        ->setPrimaryKey('goodsid')
        ->addRightButton('edit', ['href' => url('show',['id' => '__id__']), 'icon' => 'fa fa-fw fa-crosshairs', 'title' => '查看'], true)
        ->addRightButton('edit')
        ->addTopButton('disable', ['field' => 'isdel', 'title' => '还原'])
        ->addTopButton('add', ['title' => '导入', 'icon' => 'fa fa-fw fa-pencil-square-o', 'href'=> url('leading'), 'class' => 'btn btn-danger'])
        ->addTopButton('custom', ['title' => '导出', 'icon' => 'fa fa-fw fa-download', 'href'=> url('export'), 'class' => 'btn btn-info js-get'])
        ->addTopButton('add', ['title' => '返回SKU列表', 'icon' => 'glyphicon glyphicon-share-alt', 'href'=> url('index'), 'class' => 'btn btn-default'])
        ->setRowList($data_list)
        ->fetch();
    }

    public function leading(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['excelfile'])){
                $this->error('请上传文件');
            }
            $file = Db::name('admin_attachment')->where('id', $data['excelfile'])->value('path');
            $filetmpname = $_SERVER['DOCUMENT_ROOT'] . '/public/' . $file;

     
            import('util.PHPExcel', EXTEND_PATH, '.class.php');
            $PHPExcel = new \PHPExcel();
            $PHPReader = new \PHPExcel_Reader_Excel2007();
            if(!$PHPReader->canRead($filetmpname)){
                $PHPReader = new \PHPExcel_Reader_Excel5();
                if(!$PHPReader->canRead($filetmpname)){
                    $PHPReader = new \PHPExcel_Reader_CSV();
                    if(!$PHPReader->canRead($filetmpname)){
                        $this->error("no Excel");
                    }
                }
            }

            $PHPExcel = $PHPReader->load($filetmpname);
            $ids = array();
            $memberset=array();
            $sheet = $PHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();
            $errmsg = '';
            $result = false;
            $p = 1;
            for ($row = 2; $row <= $highestRow; $row++){
                $goodsno            = $sheet->getCell('A'.$row)->getValue();
                $data['goodsname']  = $sheet->getCell('B'.$row)->getValue();
                $data['cess']       = $sheet->getCell('C'.$row)->getValue();
                $color              = $sheet->getCell('D'.$row)->getValue();
                $size               = $sheet->getCell('E'.$row)->getValue();
                $data['conversion'] = $sheet->getCell('F'.$row)->getValue();
                $brand              = $sheet->getCell('G'.$row)->getValue();
                $data['weight']     = $sheet->getCell('H'.$row)->getValue();
                $class              = $sheet->getCell('I'.$row)->getValue();
                $shop               = $sheet->getCell('J'.$row)->getValue();
                $data['minprice']   = $sheet->getCell('K'.$row)->getValue();

                $p += 1;
                if(empty($goodsno) || empty($brand) || empty($class) || empty($shop)){
                    $errmsg .= '<span>第'.$p.'行,有必填信息未填</span><br/>';
                }else{
                    $data['brandid'] = BrandModel::where('brandname', $brand)->value('brandid');
                    $data['colorid'] = ColorModel::where(array('name' => "$color", 'brandid' => $data['brandid']))->value('colorid');
                    $data['sizeid']  = SizeModel::where(array('name' => "$size", 'brandid' => $data['brandid']))->value('sizeid');
                    $data['classid'] = GoodsClassModel::where('artno', $class)->value('classid');
                    $shopid = ShopModel::where('name', $shop)->value('id');

                    if(empty($data['goodsname'])){
                        unset($data['goodsname']);
                    }
                    if(empty($data['cess'])){
                        unset($data['cess']);
                    }
                    if(empty($data['conversion'])){
                        unset($data['conversion']);
                    }
                    if(empty($data['weight'])){
                        unset($data['weight']);
                    }
                    if(empty($data['minprice'])){
                        unset($data['minprice']);
                    }
                    if(empty($data['classid'])){
                        unset($data['classid']);
                    }
                    if(empty($data['brandid'])){
                        unset($data['brandid']);
                        unset($data['colorid']);
                        unset($data['sizeid']);
                    }

                    $data['bedit']  = 0;
                    $data['status'] = 0;
                    $data['checkstatus'] = 0;
                    $data['update_time'] = time();
                    $result = ProductModel::where(array('ownerid' => $shopid, 'goodsno' => $goodsno))->update($data);
                }
            }

            if($result){
                $this->success('更新成功', null, ['_close_pop' => 1]);
            }else{
                $this->error("$errmsg");
            }

        }

        return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列            
               ['importfile', 'excelfile'],
        ])
        ->fetch();

    }


    public function activites(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $data_list = ActivitesModel::select();

        return ZBuilder::make('table')
        ->addColumns([ // 批量添加列
            ['activitesname', '名称'],
            ['type', '展示类型','status', '', ['独立展示', '混合展示']],
            ['status', '状态' , 'status'],
            ['right_button', '操作', 'btn']
        ])
        ->setTableName('goods_activites')
        ->setPrimaryKey('activitesid')
        ->addRightButton('edit',['href' => url('editactivites',['id' => '__id__'])])
        ->addTopButton('add',['href' => url('addactivites')])
        ->setRowList($data_list)
        ->setPrimaryKey('activitesid')
        ->setTableName('goods_activites')
        ->fetch();
    }

    public function addactivites(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = ActivitesModel::insert($data);
            if($result) {
                $this->success('新增成功');
            }else{
                $this->error('新增失败');
            }
        }


        return ZBuilder::make('form')
        ->addFormItems([
            ['text', 'activitesname', '名称'],
            ['radio', 'type', '展示类型', '', ['0' => '独立展示', '1' => '混合展示'], '1'],
            ['radio', 'status', '状态', '', ['0' => '禁用', '1' => '启用'], '1'],
            ])
        ->layout(['activitesname' => 4, 'type' => 4, 'status' => 4])
        ->fetch();
    }

    public function editactivites($id = 0){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = ActivitesModel::update($data);
            if($result) {
                $this->success('修改成功', cookie('__forward__'));
            }else{
                $this->error('修改失败');
            }
        }

        if($id == 0){
            $this->error('参数错误');
        }
        $info = ActivitesModel::where('activitesid', $id)->find();
        return ZBuilder::make('form')
        ->addFormItems([
            ['hidden', 'activitesid'],
            ['text', 'activitesname', '名称'],
            ['radio', 'type', '展示类型', '', ['0' => '独立展示', '1' => '混合展示']],
            ['radio', 'status', '状态', '', ['0' => '禁用', '1' => '启用']],
            ])
        ->layout(['activitesname' => 4, 'type' => 4, 'status' => 4])
        ->setFormData($info)
        ->fetch();
    }

    /*public function addstock(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $add_data = [];
            $data_key = [];
            $ids      = [];
            foreach ($data as $key => $value) {
                $add_data = [];
                $data_key = [];
                $data_key = explode('_', $key);
                $add_data['totalnum']    = $value;
                $add_data['skuid']       = $data_key['1'];
                $add_data['warehouseid'] = $data_key['2'];
                if($value > 0){
                    $result = db('goods_list')->where('goodsid', $data_key['1'])->update(['status' => '1']);
                    $ids[]  = db('goods_stock')->insertGetid($add_data);
                }
            }
            if($ids) {
                $this->success('上架成功', cookie('__forward__'));
            }else{
                $this->error('上架失败');
            }
        }

        $data = input();
        if(empty($data['ids'])){
            $this->error('请至少选择一款SKU');
        }
        
        //上架SKU
        $sku_where            = [];
        $shu_where['goodsid'] = array('in',$data['ids']);
        $sku_list             = ProductModel::where($sku_where)->select();
        
        //仓库
        $warehouse_list       = db('warehouse_list')->where('status', '1')->select();

        $parm   = [];
        $layout = [];

        foreach ($sku_list as $key => $value) {
                    $parm[] = ['static', 'goodsid_'.$value['goodsid'],'名称 : '.$value['goodsname'].' ___编号 ： '.$value['goodsno']];
                    foreach ($warehouse_list as $k => $val) {
                        $parm[]  = ['text', 'warehouseid_'.$value['goodsid'].'_'.$val['warehouseid'],$val['warehousename']];
                        $layout += ['warehouseid_'.$value['goodsid'].'_'.$val['warehouseid'] => 3];
                    }
                }

        return ZBuilder::make('form')
        ->addFormItems($parm)
        ->layout($layout)
        ->fetch();        

        }*/

        public function addstock(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if(empty($data['excelfile'])){
                $this->error('请上传文件');
            }
            $file = Db::name('admin_attachment')->where('id', $data['excelfile'])->value('path');
            $filetmpname = $_SERVER['DOCUMENT_ROOT'] . '/public/' . $file;

     
            import('util.PHPExcel', EXTEND_PATH, '.class.php');
            $PHPExcel = new \PHPExcel();
            $PHPReader = new \PHPExcel_Reader_Excel2007();
            if(!$PHPReader->canRead($filetmpname)){
                $PHPReader = new \PHPExcel_Reader_Excel5();
                if(!$PHPReader->canRead($filetmpname)){
                    $PHPReader = new \PHPExcel_Reader_CSV();
                    if(!$PHPReader->canRead($filetmpname)){
                        $this->error("no Excel");
                    }
                }
            }

            $PHPExcel = $PHPReader->load($filetmpname);
            $ids = array();
            $memberset=array();
            $sheet = $PHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();
            $errmsg = '';
            $result = false;
            $p = 1;
            $add_data    = [];
            $all_update  = [];
            $all_insert  = [];
            $all_logdate = [];
            $goods_ids   = [];
            for ($row = 2; $row <= $highestRow; $row++){

                $goodsno            = $sheet->getCell('A'.$row)->getValue();
                $warehousename      = $sheet->getCell('B'.$row)->getValue();
                $totalnum           = $sheet->getCell('C'.$row)->getValue();

                $p += 1;
                if(empty($goodsno) || empty($warehousename) || empty($totalnum)){
                    $errmsg .= '<span>第'.$p.'行,有必填信息未填</span><br/>';
                }else{
                    $add_data = [];
                    $goodsno  = trim($goodsno,' ');
                    $add_data = db::name('goods_list a')
                              ->join('goods_class b', 'a.classid=b.classid', 'left')
                              ->join('goods_type c', 'b.typeid=c.typeid', 'left')
                              ->join('goods_unit d', 'b.minunit=d.unitid', 'left')
                              ->join('goods_brand e', 'a.brandid=e.brandid', 'left')
                              ->join('goods_color f', 'a.colorid=f.colorid', 'left')
                              ->join('goods_size g',  'a.sizeid=g.sizeid', 'left')
                              ->field('a.goodsid skuid,a.classid,a.ownerid storeid,b.artno,d.unitname,c.classname typename,e.brandname,f.name colorname,g.name sizename,a.goodsno')
                              ->where('a.goodsno',$goodsno)
                              ->find();
                    $warehouseid        = Db::name('warehouse_list')->where('warehousename', $warehousename)->value('warehouseid');

                    if(!empty($add_data) && !empty($warehouseid)){

                        $add_data['warehouseid'] = $warehouseid;

                        //判断是否有记录
                        $stock_info               = Db::name('goods_stock')->where(['warehouseid' => $warehouseid, 'skuid' => $add_data['skuid']])->find();

                        $add_data['totalnum'] = $totalnum;
                        $add_data['waitnum']  = $totalnum;                     
                        
                        
                        //日志
                        $log_data                = [];
                        $log_data['num']         = $totalnum;
                        $log_data['create_time'] = time();


                        if($stock_info){
                            $add_data['totalnum'] = $totalnum+$stock_info['totalnum'];
                            $add_data['waitnum']  = $totalnum+$stock_info['waitnum'];
                            $add_data['stockid']  = $stock_info['stockid'];
                            $ids[] = Db::name('goods_stock')->update($add_data);
                            if($totalnum != 0){
                                $log_data['content'] = $warehousename.' :SKU编号:'.$add_data['goodsno'].'修改库存'.$totalnum.';剩余可用库存'.$add_data['waitnum'].'。';
                                $log_data['stockid'] = $stock_info['stockid'];
                                $all_logdate[]       = $log_data;
                            }

                        }else{
                            $all_insert[] = $add_data;
                                $log_data['content'] = $warehousename.' :SKU编号:'.$add_data['goodsno'].'新增库存'.$totalnum.';剩余可用库存'.$add_data['waitnum'].'。';
                                $log_data['stockid'] = $result;
                                $all_logdate[]       = $log_data;
                        }
                        $goods_ids[] = $add_data['skuid'];                    
                }
                }
            }
            if(!empty($goods_ids)){
                $update_where['goodsid'] = array('in',$goods_ids);
                ProductModel::where($update_where)->update(['status', '1']);
            }
            if(!empty($all_insert)){
                $ids[] = Db::name('goods_stock')->insertAll($all_insert);
            }
            if(!empty($all_logdate)){
                Db::name('goods_stock_log')->insertAll($all_logdate);
            }
            if($ids){
                $this->success('上架成功', null, ['_parent_reload' => 1]);
            }else{
                if(empty($errmsg)){
                    $this->error('无修改');
                }else{
                    $this->error("$errmsg");
                }
                
            }

        }

         return ZBuilder::make('form')
        ->addFormItems([ // 批量添加列            
               ['importfile', 'excelfile'],
        ])
        ->fetch();

    }
    
 
}
